package view;

import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import model.Card;
import model.Suit;

/*
 * The purpose of this class is to preload the necessary images for MetaDeck from the images folder. 
 * This way, the image objects can be stored in memory and the desired image object can be returned
 * quickly just from a function call to loadImage.
 */
public class ImageLoader {
	/** Pixel width of the card images. Could be off by 1, don't rely on this exact value. */
	public final static int IMAGE_WIDTH = 71;
	/** Pixel height of the card images. Could be off by 1, don't rely on this exact value. */
	public final static int IMAGE_HEIGHT = 96;
	private static Map<String,Image> images;
	private static boolean fetched = false;
	static {
		fetchImages();
	}
	private ImageLoader() {
	}
	public static void prefetchImages() {
		fetchImages();
	}
	private static void fetchImages() {
		if(fetched) return;
		images = new HashMap<String, Image>();
		for(int i=1; i<=52; i++) {
			String suit = "DIAMOND";
			if(i%4==1) suit = "CLUB";
			else if(i%4==2) suit = "SPADE";
			else if(i%4==3) suit = "HEART";
			int value = 1;
			if(i>4) value = (60-i)/4;
		    images.put(value+suit, readImageFromFile(i+".png"));
		    images.put(value+suit+"s", readImageFromFile(i+".png"));
		}
		images.put("small joker", readImageFromFile("53.png"));
		images.put("big joker", readImageFromFile("54.png"));
		images.put("back", readImageFromFile("b1fv.png"));
		fetched = true;
	}
	private static Image readImageFromFile(String fileName) {
		Image image = null;
	    try {
	        File sourceimage = new File("images/"+fileName);
	        image = ImageIO.read(sourceimage);
	    
	    } catch (IOException e) {
	    }
	    return image;
	}
	
	/*
	 * Public method for loading images. The argument should be the name of the image desired. 
	 * An Image object is returned.
	 * 
	 * Possible image names:
	 * -number followed by suit, i.e. 3HEART, 11CLUB, 13SPADE, 1DIAMOND
	 * -small joker
	 * -big joker
	 * -back
	 */
	public static Image loadImage(String name) {
		return images.get(name);
	}
	public static Image loadImage(Card card) {
		if(card==null) 
			return null;
		if(card.suit!=Suit.JOKER) //If not a joker
			return loadImage(card.value+""+card.suit);
		if(card.value==14 && card.suit==Suit.JOKER)
			return loadImage("small joker");
		if(card.value==15 && card.suit==Suit.JOKER)
			return loadImage("big joker");
		//Invalid card data
		return null;
	}
}
